import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import ying.model.Student;

import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * ClassName: MybatisDemo02
 * Package: PACKAGE_NAME
 * Description:
 *
 * @Author 刘英杰
 * @Create 2024/11/1 14:44
 * @Version 1.0
 */
public class MybatisDemo02 {
    @Test
    public void testInsertStudent() {
        InputStream is = MybatisDemo02.class.getClassLoader().getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2000-10-10");
            java.sql.Date date1 = new java.sql.Date(date.getTime());
            Student student = new Student("张三三", "男", date1);
            sqlSession.insert("test.insertStudent",student);

            sqlSession.commit();
            System.out.println(student);
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        }

    }

    @Test
    public void testUpdateStudent() {
        InputStream is = MybatisDemo02.class.getClassLoader().getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {
//            Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2020-02-20");
//            java.sql.Date birthday = new java.sql.Date(date.getTime());
//            Student student = new Student(201215157, "张三四", "男", birthday);
//            sqlSession.update("test.updateStudent",student);

            //以上合并
            sqlSession.update("test.updateStudent",new Student(201215157, "张三五", "男",
                    new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse("2020-02-20").getTime())));

            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        }finally {
            sqlSession.close();
        }

    }

    @Test
    public void testDeleteStudent() {
        InputStream is = MybatisDemo02.class.getClassLoader().getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = null;
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {
            sqlSession.delete("test.deleteStudent",201215157);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            sqlSession.close();
        }

    }


}
